'use strict'

const { ApiController } = require('jax')

class Controller extends ApiController {
  // 模型
  get Model() {
    return this.ctx.model.Article
  }

  // 匹配查询
  get searchKey() {
    return ['app', 'categoryId', 'title']
  }

  // 模糊查询
  get likeKey() {
    return []
  }

  // 返回JSON字段
  get json() {
    return ['id', 'title', 'cover', 'createdAt', 'type']
  }

  // 查询前
  async beforeIndex() {
    const { ctx } = this
    const { query } = ctx

    const filter = {
      isOpen: true,
    }

    if (query.categoryName) {
      await this.ctx.model.ArticleCategory.findOne({
        categoryName: query.categoryName,
        isOpen: true,
      }).then((category) => {
        if (!category) throw '未知的分类名称'
        filter.categoryId = category._id
      })
    }

    return {
      filter,
      sort: {
        isTop: 'DESC',
        rank: 'ASC',
      },
    }
  }

  async afterShow(doc) {
    this.viewTrack(doc)
  }

  // 格式化
  async formatData(item) {
    const newItem = this.toJson(item, this.json)

    if (item.type == 'text') newItem.content = item.content
    else if (item.type == 'image') newItem.images = item.images
    else if (item.type == 'link') newItem.link = item.link
    else if (item.type == 'path') newItem.path = item.path
    else if (item.type == 'html') newItem.html = item.html

    return newItem
  }

  // 文章访问统计(PV/UV)
  async viewTrack(doc, userId) {
    const { ctx } = this

    const logData = {
      type: 'article',
      docId: doc.id,
      sourceId: userId,
    }

    const todayRecord = await ctx.model.TrackLog.findOne(logData)

    const newData = {
      pv: 1,
    }

    // 今日无访问记录增加UV
    if (!todayRecord) newData.uv = 1

    await ctx.model.Article.updateOne(
      { _id: doc.id },
      {
        $inc: newData,
      }
    )

    await ctx.model.TrackLog.create(logData)
  }
}

module.exports = Controller
